﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Platform.Storage.Entity;
using Platform.ObjectModel;
using Platform.ObjectModel.Design;

namespace Platform.Storage.Impl
{
	internal sealed class DefaultQueryExpander : IQueryResolver
	{
		private IEnumerable<Tuple<Type, DataObjectName>> names;

		internal DefaultQueryExpander( IQueryable<FieldValue> fields, IQueryable<DataObjectRelationship> relations, IEnumerable<Tuple<Type, DataObjectName>> names )
		{
			this.Fields = fields;
			this.Relations = relations;
			this.names = names;
		}

		#region IQueryExpander Members

		public IQueryable<FieldValue> Fields
		{
			get;
			private set;
		}

		public IQueryable<FieldValue> Index
		{
			get { return this.Fields; }
		}

		public bool TryGetSchema( Type entityType, out Schema schema )
		{
			throw new NotImplementedException();
		}

		public DataObjectName GetDataObjectName( Type entityType )
		{
			var name = this.names.FirstOrDefault( pair => pair.Item1 == entityType );

			if ( name != null )
				return name.Item2;
			else
				throw new InvalidOperationException( String.Format( "O nome não foi encontrado para o tipo \"{0}\".", entityType.FullName ) );
		}

		public DataObjectName GetFieldKey( Type entityType )
		{
			DataObjectName name = this.GetDataObjectName( entityType );
			//return name.FieldNameWithSchema( "Id" );
			return new DataObjectName( "Id", name.Namespace );
		}

		#endregion

		#region IQueryResolver Members


		public IQueryable<DataObjectRelationship> Relations
		{
			get;
			private set;
		}

		#endregion
	}
}
